#include <iostream>
#include<unordered_map>
#include<algorithm>
#include<math.h>
using namespace std;
class Solution {
public:
    bool isTrue(const string& s1, const string& s2) {
        int cnt = 0;
        for (int i = 0; i < s1.size(); i++)
            if (s1[i] != s2[i])
                cnt++;
        return cnt == 1;
    }
    vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) {
        vector<string>ans;
        vector<int>dp(n, 1), p(n, -1);
        for (int i = 0; i < n; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (groups[i] == groups[j] || words[i].size() != words[j].size() || !isTrue(words[i], words[j])) continue;
                if (dp[j] + 1 > dp[i])
                {
                    dp[i] = dp[j] + 1;
                    p[i] = j;
                }
            }
        }
        int x = max_element(dp.begin(), dp.end()) - dp.begin();
        while (x != -1) {
            ans.push_back(words[x]);
            x = p[x];
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};